import os

def process_srt(input_file, output_file):
    """
    处理srt文件，去除时间戳行并保存为新文件

    参数:
    input_file (str): 输入srt文件的路径
    output_file (str): 输出文件的路径
    """
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()

        # 用于存储处理后的行
        processed_lines = []

        i = 0
        while i < len(lines):
            line = lines[i].strip()

            # 跳过空行
            if not line:
                i += 1
                continue

            # 检查是否为数字编号行（第一行）
            if line.isdigit():
                processed_lines.append(line + '\n')
                i += 1

                # 跳过时间戳行
                if i < len(lines):
                    i += 1

                # 添加字幕内容
                while i < len(lines) and lines[i].strip() != "":
                    processed_lines.append(lines[i])
                    i += 1
            else:
                i += 1

        # 写入新文件
        with open(output_file, 'w', encoding='utf-8') as f:
            f.writelines(processed_lines)

        print(f"处理完成！结果已保存到: {output_file}")

    except Exception as e:
        print(f"处理文件时出错: {str(e)}")


def merge_srt(original_srt, edited_content, output_srt):
    """
    合并原始srt文件和编辑后的内容，生成新的srt文件

    参数:
    original_srt (str): 原始srt文件路径
    edited_content (str): 编辑后的内容文件路径
    output_srt (str): 输出的新srt文件路径
    """
    try:
        # 读取编辑后的内容文件，创建编号到内容的映射
        edited_dict = {}
        current_number = None
        current_content = []

        with open(edited_content, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line.isdigit():
                    if current_number is not None:
                        edited_dict[current_number] = current_content
                        current_content = []
                    current_number = line
                elif line:
                    current_content.append(line)

        # 保存最后一个条目
        if current_number is not None:
            edited_dict[current_number] = current_content

        # 读取原始srt文件并创建新文件
        with open(original_srt, 'r', encoding='utf-8') as f:
            lines = f.readlines()

        new_lines = []
        i = 0
        while i < len(lines):
            line = lines[i].strip()

            # 跳过空行
            if not line:
                new_lines.append('\n')
                i += 1
                continue

            # 如果是数字编号行
            if line.isdigit():
                number = line
                new_lines.append(line + '\n')  # 添加编号
                i += 1

                # 添加时间戳行
                if i < len(lines):
                    new_lines.append(lines[i])  # 保持原有的时间戳
                    i += 1

                # 添加新的内容
                if number in edited_dict:
                    for content_line in edited_dict[number]:
                        new_lines.append(content_line + '\n')

                # 跳过原内容直到下一个编号或文件结束
                while i < len(lines) and not lines[i].strip().isdigit() and lines[i].strip():
                    i += 1
            else:
                i += 1

        # 写入新文件
        with open(output_srt, 'w', encoding='utf-8') as f:
            f.writelines(new_lines)

        print(f"合并完成！新的srt文件已保存到: {output_srt}")

    except Exception as e:
        print(f"合并文件时出错: {str(e)}")


# 使用示例
if __name__ == "__main__":
    # 第一步：处理原始srt文件
    input_file = "C:\\Users\\X\\Desktop\\字幕\\src.srt"
    output_file = "C:\\Users\\X\\Desktop\\字幕\\out.zm"
    language_codes = ['ar', 'bg','bn','sw', 'pl', 'fa', 'da', 'de', 'ru', 'fr', 'fi', 'ko', 
                 'nl', 'cs', 'hr', 'ro', 'ms', 'no', 'pa', 'pt', 'ja', 'sv', 
                 'sr', 'ta', 'th', 'tr', 'ur', 'es', 'he', 'el', 'hu', 'it', 
                 'hi', 'id', 'en', 'vi', 'zh', 'zh-Hant']
    process_srt(input_file, output_file)
    for lang in language_codes:
       open(f'C:\\Users\\X\\Desktop\\字幕\\zm\\{lang}.zm', 'w').close()
    os.system("pause")
